'use strict';

module.exports = app => {
  class UserController extends app.Controller {
    async list (ctx) {
      let results = await ctx.app.model.user.doc.find().limit(10)

      let total = await ctx.app.model.user.doc.count()

      if (!results || !results.length) {
        ctx.helper.rest.resp({
          ctx,
          code: 1,
          error: 'Not Found'
        })
        return
      }

      ctx.helper.rest.resp({
        ctx,
        code: 0,
        data: {
          total,
          list: results.map(x => x.toObject({
            virtuals: true,
            transform: function (doc, ret, options) {
              delete ret._id
              return ret
            }
          }))
        }
      })
    }

    async init (ctx) {
      let super_admin = new ctx.app.model.user.doc({
        username: 'admin',
        password: 'admin',
        user_type: 'super_admin'
      })

      // super_admin.password = super_admin.hash_password
      let res = await super_admin.save().catch(ctx.helper.genAppError({ctx}))

      if (ctx.helper.abortOnError({
        ctx,
        error: res,
        code: res.code,
        message: 'fail to init'
      })) return

      ctx.helper.rest.resp({
        ctx,
        code: 0,
        message: 'init finished.'
      })
    }

    async drop () {
      ctx.helper.rest.resp({
        ctx,
        code: 206,
        message: 'dangerous action, do it manully.'
      })
    }
  }

  return UserController
}
